In todobackend/api/views.py, add the below perform_create method:

Modify Bold Code

...

class TodoListCreate(generics.ListCreateAPIView):

# ListAPIView requires two mandatory attributes, serializer_class and

# queryset.

# We specify TodoSerializer which we have earlier implemented

serializer_class = TodoSerializer

def get_queryset(self):

user = self.request.user

return Todo.objects.filter(user=user).order_by('-created')

def perform_create(self, serializer):

#serializer holds a django model

serializer.save(user=self.request.user)

perform_create acts as a hook which is called before the instance is created in the database. Thus, we can specify

that we set the user of the todo as the request’s user before creation in the database.

These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the

request data. In our case, we set the todo’s user based on the request user.

See how Django allows many auto-generated features yet also allow these customizations?

Running your App

When you attempt to add a todo via the form now, your todo should be successfully added. If you reload the

endpoint at localhost:8000/api/todos/, the new todo should be in the JSON results.